package com.hp.common.validator;

import com.hp.common.annotation.PhoneValidator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

public class PhoneValidatorClass implements ConstraintValidator<PhoneValidator, String> {

    private final Pattern pattern = Pattern.compile("^1[3456789]\\d{9}$");
    private boolean required;

    @Override
    public void initialize(PhoneValidator validator) {
        this.required = validator.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (this.required) {
            if (null == value || "".equals(value)) {
                return false;
            }
        }
        return pattern.matcher(value).matches();
    }
}
